import React, { useCallback } from "react"
import { Field_FormSave, Field_name_Role_Id } from "@/components/utils/field.list"
import { FormProps } from "@/components/modal/form.modal"
import adminRulesService from "@/services/admin.rules.service"
import adminPermissionsService from "@/services/admin.permission.service"
import { FormRender } from "@whzhuke/antd"
import { useFetch } from "@whzhuke/usehook"
import useForm from "antd/es/form/hooks/useForm"
interface Props {
  values?: any
}
interface Props {
  roleId: number
}
export const BindRulesPermission: React.FC<Props & FormProps> = props => {
  const { roleId, onDone } = props

  const [form] = useForm<any>()
  const onFinish = useCallback(
    value => {
      adminRulesService["distributePermissions"]({ roleId: roleId, permissionIdList: [value.permissionIdList] }).then(res => {
        onDone?.()
      })
    },
    [roleId]
  )
  const [{ data: permissionList }] = useFetch(adminPermissionsService.queryAll, [{ keyword: "" }])
  const [{ data: havePermissionList }] = useFetch(adminRulesService.queryHavePermissions, [{ id: roleId }])
  return (
    <FormRender
      form={form}
      initialValues={{ roleId, permissionIdList: havePermissionList.map(m => m) }}
      layout="horizontal"
      onFinish={onFinish}
      labelCol={{ span: 8 }}
      wrapperCol={{ span: 16 }}
      style={{ width: 600 }}
      fieldList={[
        roleId ? Field_name_Role_Id : undefined,
        {
          fieldType: "select",
          formItemConfig: { name: "permissionIdList", label: "所属权限", required: !0 },
          config: {
            placeholder: "请选择权限",
            options: permissionList.map((v: { permissionName: any; id: any }) => ({ label: v.permissionName, value: v.id }))
          }
        },
        { ...Field_FormSave, formItemConfig: { wrapperCol: { offset: 8, span: 16 } } }
      ]}
      autoComplete="off"
    />
  )
}
